<?php
namespace Admin\Controller;

use Think\Controller;

class SystemsController extends Controller
{
    /**
     * 子账户列表
     */
    public function admin_list()
    {
        $info = M('shopkeeper', '', 'XYC');
        $merchant_role_db=M('merchant_role','','XYC');
        $communication_db=D('Communication');
        $where = MycommonController::set_where(array(), array('account', 'name', 'mobile'));
        $where['state'] = ['neq', '-1'];
        $where['rid'] = ['neq', '99'];
        $where['shop_idenfier']=$_SESSION['shop_identifier'];
        $tol = $info->WHERE($where)->COUNT();
        $row = '10';
        $page = new PageController($tol, $row);
        $fpage = $page->fpage();
        $list = $info->WHERE($where)->ORDER('ctime desc')->LIMIT($page->listfirst, $page->listRows)->SELECT();
        foreach ($list as $k => $v) {
            $list[$k]['rolename']=$merchant_role_db->WHERE(['id'=>['in',$v['rid']]])->getField('rolename',true);
            $list[$k]['rolename']=implode(',',$list[$k]['rolename']);
            $list[$k]['ctime'] = date('Y-m-d', $v['ctime']);
            $list[$k]['nickname']=$communication_db->WHERE(['shop_id'=>$v['id']])->getField('nickname');
        }
        $roles = M('merchant_role', '', 'XYC')->WHERE("status=1 and id!=6 and version=2")->SELECT();
        $this->assign(array(
            'list' => $list,
            'role' => json_encode($roles),
            'fpage' => $fpage,
            'tol' => $tol
        ));
        $this->display();
    }

    /**
     * 添加管理员账号
     */
    public function add_admin()
    {
        $info = D('Admin');
        if (!empty($_POST)) {
            $data['shop_idenfier'] = $_SESSION['shop_identifier'];
            $data['account'] = I('account');
            $data['password'] = I('pwd');
            $data['mobile'] = I('mobile');
            $data['name'] = I('name');
            $data['email'] = I('email');
            $data['qq'] = I('qq');
            $data['rid'] = I('rid');
            $data['is_hide'] = I('privacy');
            $data['ctime'] = time();
            if ((in_array('4', explode(',', I('rid'))) || in_array('10', explode(',', I('rid')))) && (empty(I('qq')) || empty(I('nickname')))) {
                MycommonController::ajax('1002', '客服角色必须填写QQ号和昵称', 'error');
            }
            $res = $info->create($data, 1);
            if (!$res) {
                MycommonController::ajax('1002', $info->getError(), 'error');
            }
            $res = $info->add();
            if ($res) {
                if (in_array('4', explode(',', I('rid'))) || in_array('10', explode(',', I('rid')))) {
                    $data['id'] = $res;
                    $data['nickname'] = I('nickname');
                    $info->kefu_handle($data);
                }
                $content = '添加了管理员' . I('account');
                add_control_log($_SESSION['shop_identifier'], $_SESSION['account'], $content, '3');
                MycommonController::ajax('1001', '添加成功');
            } else {
                MycommonController::ajax('1002', '添加失败', 'error');
            }
        }
    }

    /**
     * 修改子账号信息
     */
    public function modify_admin()
    {
        $info = D('Admin');
        if (!empty($_POST)) {
            $data['id']=I('id');
            $data['shop_idenfier'] = $_SESSION['shop_identifier'];
            $data['mobile'] = I('mobile');
            $data['name'] = I('name');
            $data['email'] = I('email');
            $data['qq'] = I('qq');
            $data['rid'] = I('rid');
            $data['is_hide'] = I('privacy');
            if(in_array('10',explode(',',I('rid'))) && (empty(I('qq')) || empty(I('nickname')))){
                MycommonController::ajax('1002', '客服角色必须填写QQ号和昵称', 'error');
            }

            $res = $info->create($data, 2);
            if (!$res) {
                MycommonController::ajax('1002', $info->getError(), 'error');
            }
            $res = $info->WHERE(['id'=>$data['id'],'shop_idenfier'=>$_SESSION['shop_identifier']])->SAVE($data);
            if ($res!==false) {
                $msg=$info->WHERE(['id'=>I('id')])->FIND();
                if(in_array('4',explode(',',I('rid')))  || in_array('10',explode(',',I('rid'))) ){
                    $data['account']=$msg['account'];
                    $data['nickname']=I('nickname');
                    $info->kefu_handle($data);
                }
                $content = '修改账号【' . $msg['account'].'】的信息';
                add_control_log($_SESSION['shop_identifier'], $_SESSION['account'], $content, '3');
                MycommonController::ajax('1001', '修改成功');
            } else {
                MycommonController::ajax('1002', '修改失败', 'error');
            }
        }
    }

    /**
     * 重置管理员登录密码
     */
    public function reset_pwd()
    {
        $info = D('Admin');
        if (!empty($_POST)) {
            $aid = I('aid');
            $res=$info->reset_pwd($aid);
            if (is_array($res)) {
                $content = '重置【' . $res['account'] . '】的登录密码';
                add_control_log($_SESSION['shop_identifier'], $_SESSION['account'], $content, '3');
                MycommonController::ajax('1001', '重置成功，密码【A123456】');
            } else {
                MycommonController::ajax('1002', '重置失败', 'error');
            }
        }
    }

    /**
     * 禁止/解除禁止管理员账号
     */
    public function forbid_admin()
    {
        $info = D('Admin');
        if (!empty($_POST)) {
            $aid = I('aid');
            $status = I('status');
            $res=$info->set_status($aid,$status);
            if ($status == '1') {
                $lock = '解禁';
            } else {
                $lock = '禁止';
            }
            if (is_array($res)) {
                $content = '对【'.$res['account'] . '】账号进行'.$lock.'操作';
                add_control_log($_SESSION['shop_identifier'], $_SESSION['account'], $content, '3');
                MycommonController::ajax('1001', '操作成功');
            } else {
                MycommonController::ajax('1002', '操作失败', 'error');
            }
        }
    }

    /**
     * 删除管理员
     */
    public function del_admin()
    {
        $info = D('Admin');
        if (!empty($_POST)) {
            $aid = I('aid');
            $res=$info->set_status($aid,'-1');
            if (is_array($res)) {
                $content = '删除账号【' .$res['account'].'】' ;
                add_control_log($_SESSION['shop_identifier'], $_SESSION['account'], $content, '3');
                MycommonController::ajax('1001', '删除成功');
            } else {
                MycommonController::ajax('1002', '删除失败', 'error');
            }
        }
    }

    /**
     * 客服管理
     */
    public function kefu_list()
    {
        $info = M('shopkeeper', '', 'XYC');
        $where = MycommonController::set_where(array(), array('s.account', 's.name', 's.mobile'));
        $where['s.state'] = ['neq', '-1'];
        $where['s.shop_idenfier']=$_SESSION['shop_identifier'];
        $where['sr.rid']='4';
        $tol = $info->JOIN("s join shopkeeper_role sr on s.id=sr.sid")->WHERE($where)->COUNT();
        $row = '10';
        $page = new PageController($tol, $row);
        $fpage = $page->fpage();
        $list = $info->JOIN("s join shopkeeper_role sr on s.id=sr.sid")->WHERE($where)->FIELD("s.*")->ORDER('s.id desc')->LIMIT($page->listfirst, $page->listRows)->SELECT();
        foreach ($list as $k => $v) {
            $kefu_msg=D('Communication')->WHERE(['shop_id'=>$v['id']])->FIND();
            $list[$k]['ctime'] = date('Y-m-d H:i:s', $v['ctime']);
            $list[$k]['commun_type']=$kefu_msg['commun_type'];
            $list[$k]['qq']=$kefu_msg['qq'];
            $list[$k]['wx']=$kefu_msg['wx'];
            $list[$k]['nickname']=$kefu_msg['nickname'];
        }
        $this->assign(array(
            'list' => $list,
            'fpage' => $fpage,
            'tol' => $tol
        ));
        $this->display();
    }


    /**
     * 修改客服资料
     */
    public function modify_kefu()
    {
        if (!empty($_POST)) {
            $info = D('Communication');
            $admin_msg=D('Admin')->WHERE(['id'=>I('shop_id')])->FIND();
            $data['shop_identifier'] = $_SESSION['shop_identifier'];
            $data['nickname'] = I('nickname');
            $data['qq'] = I('qq');
            $data['wx'] = I('wx');
            $data['shop_id'] = I('shop_id');
            $data['account'] = $admin_msg['account'];
            $data['ctime'] = time();
            if(empty(I('qq')) && empty(I('wx'))){
                MycommonController::ajax('1002', 'QQ号和微信号至少填一项', 'error');
            }
            $res = $info->create($data);
            if (!$res) {
                MycommonController::ajax('1002', $info->getError(), 'error');
            }
            if(!empty($info->WHERE(['shop_id'=>$data['shop_id']])->getField('id'))){
                $res = $info->WHERE(['shop_id'=>$data['shop_id']])->SAVE();
                if(!$res)  MycommonController::ajax('1002', '修改失败', 'error');
            }else{
                $res = $info->add();
                if($res===false)  MycommonController::ajax('1002', '修改失败', 'error');
            }
            $content = '修改客服【' . $admin_msg['account'].'】的资料';
            add_control_log($_SESSION['shop_identifier'], $_SESSION['account'], $content, '3');
            MycommonController::ajax('1001', '修改成功');

        }
    }

    /**
    * 登录日志
    */
    public function login_log(){
        $info=M('login_log','','XYC');
        $where = MycommonController::set_where(array(), array('account', 'name'), 'login_time',array('location'));
        $where['shop_idenfier']=$_SESSION['shop_identifier'];
        $tol = $info->WHERE($where)->COUNT();
        $row = '15';
        $page = new PageController($tol, $row);
        $fpage = $page->fpage();

        $list = $info->WHERE($where)->FIELD("id")->LIMIT($page->listfirst, $page->listRows)->ORDER("id desc")->SELECT();
        $list = array_column($list, 'id');
        $list = $info->WHERE(['id' => ['in', $list]])->ORDER("id desc")->SELECT();
        foreach ($list as $k => $v) {
            $list[$k]['login_time'] = date('Y-m-d H:i:s', $v['login_time']);
        }
        $this->assign(array(
            'list' => $list,
            'fpage' => $fpage,
            'tol' => $tol
        ));
        $this->display();
    }

    /**
     * 内控日志
     */
    public function inside_control_log(){
        $info=M('control_log','','XYC');
        $where = MycommonController::set_where(array(), array('name'), 'ctime',array('content'));
        $where['shop_identifier']=$_SESSION['shop_identifier'];
        $tol = $info->WHERE($where)->COUNT();
        $row = '15';
        $page = new PageController($tol, $row);
        $fpage = $page->fpage();

        $list = $info->WHERE($where)->FIELD("id")->LIMIT($page->listfirst, $page->listRows)->ORDER("id desc")->SELECT();
        $list = array_column($list, 'id');
        $list = $info->WHERE(['id' => ['in', $list]])->ORDER("id desc")->SELECT();
        foreach ($list as $k => $v) {
            $list[$k]['ctime'] = date('Y-m-d H:i:s', $v['ctime']);
        }
        $this->assign(array(
            'list' => $list,
            'fpage' => $fpage,
            'tol' => $tol
        ));
        $this->display();
    }

    /**
     * 工作流控制
     */
    public function work_control(){
        $info=M('workflow','','XYC');
        $merchant_db=M('merchant','','XYC');
        $where = MycommonController::set_where(array(), array('name'), 'ctime',array('content'));
        $where['shop_identifier']=$_SESSION['shop_identifier'];
        $tol = $info->WHERE($where)->COUNT();
        $row = '15';
        $page = new PageController($tol, $row);
        $fpage = $page->fpage();
        $list = $info->WHERE($where)->FIELD("id")->LIMIT($page->listfirst, $page->listRows)->ORDER("id desc")->SELECT();
        $list = array_column($list, 'id');
        $list = $info->WHERE(['id' => ['in', $list]])->ORDER("id desc")->SELECT();
        foreach($list as $k=>$v){
            $list[$k]['merchant_name']=$merchant_db->WHERE(['shop_identifier'=>$v['shop_identifier']])->getField('merchant_name');
        }
        $this->assign(array(
            'list' => $list,
            'fpage' => $fpage,
            'tol' => $tol
        ));
        $this->display();
    }

    /**
     * 工作流控制
     */
    public function upd_work_control(){
        if(!empty($_POST)){
            $data['terminal']=I('tt');
            $data['lender']='1';
//            $data['approver']=I('aa');
//            $data['marketing']=I('mm');
            $data['taobao']=I('bb');
            $data['alipay']=I('alipay');
            $data['credit_card']=I('credit_card');
            if(empty(M('workflow','','XYC')->WHERE(['id'=>I('id'),'shop_identifier'=>$_SESSION['shop_identifier']])->getField('id'))){
                MycommonController::ajax('1002','状态异常，无法修改');
            }
            $old_msg=M('workflow','','XYC')->WHERE(['id'=>I('id'),'shop_identifier'=>$_SESSION['shop_identifier']])->FIND();
            $result=array_diff($data,$old_msg);
            $res=M('workflow','','XYC')->WHERE(['id'=>I('id'),'shop_identifier'=>$_SESSION['shop_identifier']])->SAVE($data);
            if($res!==false){
                $modify='';
                if(!empty($result)){
                    foreach($result as $k=>$v){
                        switch($k){
                            case 'terminal':
                                $name='终端客服启动状态';
                                break;
                            case 'lender':
                                $name='出借人自动分配';
                                break;
                            case 'approver':
                                $name='审核员自动分配';
                                break;
                            case 'marketing':
                                $name='营销自动分配';
                                break;
                            case 'taobao':
                                $name='淘宝认证';
                                break;
                            case 'alipay':
                                $name='支付宝认证';
                                break;
                            case 'credit_card':
                                $name='信用查认证';
                                break;
                        }

                        switch($v){
                            case '1':
                                $status='启动';
                                break;
                            case '2':
                                $status='关闭';
                                break;
                        }
                        $modify.='将【'.$name.'】设置为【'.$status.'】状态,';
                    }
                }
                $modify=empty($modify)?'无修改':trim($modify,',');
                add_control_log($_SESSION['shop_identifier'],$_SESSION['account'],$modify,'3');
                MycommonController::ajax('1001','操作成功');
            }else{
                MycommonController::ajax('1002','操作失败');
            }
        }
    }

    /**
     * 基础认证规则控制
     */
    public function rule_control(){
        $list=M('user_risk_rule','','XYC')->WHERE(['shop_identifier'=>$_SESSION['shop_identifier']])->SELECT();

        $this->assign([
            'list'=>$list
        ]);
        $this->display();
    }

    public function upd_rule_control(){
        if(!empty($_POST)){
            $user_risk_rule_db=M('user_risk_rule','','XYC');
            $id=I('id');
            $detail=I('detail');
            $old_msg=$user_risk_rule_db->WHERE(['shop_identifier'=>$_SESSION['shop_identifier'],'id'=>$id])->FIND();
            switch($old_msg['rule_code']){
                case 'K0031':
                    $detail=implode(',',array_unique(explode(',',$detail)));
                    break;
                case 'K0035':
                    $detail=implode(',',array_unique(explode(',',$detail)));
                    break;
            }
            $res=$user_risk_rule_db->WHERE(['shop_identifier'=>$_SESSION['shop_identifier'],'id'=>$id])->save(['rule_detail'=>$detail,'upd_time'=>time()]);
            if($res!==false){
                add_control_log($_SESSION['shop_identifier'],$_SESSION['account'],"将".$old_msg['rule_code']."规则详情从【".$old_msg['rule_detail']."】修改为【".$detail.'】','3');
                MycommonController::ajax('1001','操作成功');
            }else{
                MycommonController::ajax('1002','操作失败');
            }
        }

    }

    /**
     * 参数设置
     */
    public function merchant_param(){
        // $shop_identifier = '0100010020';
        $shop_identifier = $_SESSION['shop_identifier'];
        $data = M('merchant','','XYC')->where(array('shop_identifier'=>$shop_identifier))->find();
        if(IS_POST){
            $interest=I('interest');
            $overdue_money=I('overdue_money');
            $overdue_day=I('overdue_day');
            $borrowing_cycle=I('borrowing_cycle');
            $font_interest=I('font_interest',0);
            $res = M('merchant','','XYC')->where(array('shop_identifier'=>$shop_identifier))->save(array('day_interest'=>$interest,'font_interest'=>$font_interest,'late_fee'=>$overdue_money,'late_days'=>$overdue_day,"borrowing_cycle"=>$borrowing_cycle));

            if($res){
                M('merchant_param_record','','XYC')->add(array('day_interest'=>$interest,'font_interest'=>$font_interest,'late_fee'=>$overdue_money,'late_days'=>$overdue_day,"borrowing_cycle"=>$borrowing_cycle,'shop_identifier'=>$shop_identifier,'ctime'=>time()));

                add_control_log($_SESSION['shop_identifier'],$_SESSION['name'],"编辑了参数设置",3);
                $data['code'] = 1001;
                $data['result'] = "设置成功！";
                $this->ajaxReturn($data);
            }elseif($res===0){
                $data['code'] = 1001;
                $data['result'] = "设置成功！";
                $this->ajaxReturn($data);
            }else{
                $data['code'] = 1002;
                $data['result'] = "设置失败！";
                $this->ajaxReturn($data);
            }
        }
        $this->assign('data',$data);
        $this->display();
    }

    /**
     * 出借人管理
     */
    public function lender_list()
    {
        $certificate_db = M('lender', '', 'XYC');
        $where = MycommonController::set_where(array(''), array('name', 'idcard','mobile'), '');
        $where['shop_idenfier'] = $_SESSION['shop_identifier'];
        $where['is_delete'] = ['neq',-1];
        $tol = $certificate_db->WHERE($where)->COUNT();
        $row = '10';
        $page = new PageController($tol, $row);
        $fpage = $page->fpage();
        $list = $certificate_db->WHERE($where)->FIELD("id")->LIMIT($page->listfirst, $page->listRows)->ORDER("id desc")->SELECT();
        $list = array_column($list, 'id');
        $list = $certificate_db->WHERE(['id' => ['in', $list]])->ORDER("is_delete asc,id desc")->SELECT();


        foreach ($list as $k => $v) {
            $list[$k]['ctime'] = date('Y-m-d H:i:s', $v['ctime']);
            if($_SESSION['is_hide']=='2'){
                $list[$k]['idcard'] = set_privacy($v['idcard'],'2');
            }

            //借出金额
            $b_money=M('vz_loan','','XYC')->where(['lender_id'=>$v['id'],'is_success'=>2])->sum('loan_amount');
            $list[$k]['b_money']=empty($b_money)?0:$b_money;

            //借款用户数
            $list[$k]['b_count']=M('vz_loan','','XYC')->where(['lender_id'=>$v['id'],'is_success'=>2])->count();

            //收利
            $font_m=M('vz_loan','','XYC')->where(['lender_id'=>$v['id'],'is_success'=>2])->sum('fee');
//            $list[$k]['font_money']=empty($font_m)?0:$font_m;

            $day_interest_money=M('vz_loan','','XYC')->where(['lender_id'=>$v['id'],'is_success'=>2,'status'=>2])->sum('day_interest_money');
//            $list[$k]['day_interest_money']=empty($day_interest_money)?0:$day_interest_money;
            $list[$k]['interest_money']=empty($font_m)?0:$font_m +empty($day_interest_money)?0:$day_interest_money;



        }
        $this->assign(array(
            'list' => $list,
            'fpage' => $fpage,
            'tol' => $tol
        ));
        $this->display();
    }

    /**
     * 添加出借人
     */
    public function add_lender()
    {
        if (!empty($_POST)) {
            $lender_db = D('Lender');
//            if(empty(I('signature'))){
//                MycommonController::ajax('1002', '签名不能为空');
//            }
//            $file_name='./Public/'.time().rand(1000,9999).'.jpg';
//            file_put_contents($file_name,base64_decode(str_replace('data:image/png;base64,','',I('signature'))));
//            $res=MycommonController::addossimg($file_name);
//            if($res===false){
//                MycommonController::ajax('1002', '签名上传失败');
//            }
//            unlink($file_name);
            $data['shop_idenfier'] = $_SESSION['shop_identifier'];
            $data['name'] = I('name');
            $data['mobile'] = I('mobile');
            $data['idcard'] = I('idcard');
//            $data['signature'] = $res;
            $data['ctime'] =time();
            $res = $lender_db->create($data);
            if ($res) {
                $res = $lender_db->add();
                if ($res) {

                    add_control_log($_SESSION['shop_identifier'],$_SESSION['account'],"添加出借人，名为【".$data['name'].'-'.$data['idcard'].'】','3');
                    MycommonController::ajax('1001', '添加成功');
                } else {
                    MycommonController::ajax('1002', '系统错误，请联系管理员');
                }
            } else {
                MycommonController::ajax('1002', $lender_db->getError());
            }
        }
    }

    /**
     * 删除出借人
     */
    public function del_lender()
    {
        if (!empty($_POST)) {
            $lender_db = D('Lender');
            $idcard = I('idcard');
            $res = $lender_db->del_lender($idcard);
            if ($res === true) {
                add_control_log($_SESSION['shop_identifier'],$_SESSION['account'],"删除出借人【".$idcard.'】','3');
                MycommonController::ajax('1001', '删除成功');
            } else {
                MycommonController::ajax('1002', $res);
            }
        }
    }

    /**
     * 设置为出借人
     */
    public function set_lender(){
       $lender_id=I('lender_id');
       $type=I('type');
       $update=M('lender','','XYC')->where(['id'=>$lender_id])->setfield('is_delete',$type);

        if($update){
//            M('lender','','XYC')->where(['id'=>['neq',$lender_id],'shop_idenfier'=>$_SESSION['shop_identifier']])->setfield('is_select',2);
            MycommonController::ajax('1001', '设置成功');
        }else{
            MycommonController::ajax('1002','设置失败');
        }
    }




}